package files;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class FileServer1 {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress("192.168.31.71", 8080));
        serverSocketChannel.configureBlocking(false);
        Selector selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4096);
        while (selector.select()>0) {
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
            while (keyIterator.hasNext()) {
                SelectionKey selectionKey = keyIterator.next();
                keyIterator.remove();
                if (selectionKey.isAcceptable()) {
                    ServerSocketChannel s = (ServerSocketChannel) selectionKey.channel();
                    SocketChannel socketChannel = s.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ);
                }else if (selectionKey.isReadable()) {
                    byteBuffer.clear();
                    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();

                    while (true) {
                        int length =  socketChannel.read(byteBuffer);
                        if (length < 0) {
                            System.out.println("socket closeing");
                            socketChannel.close();
                            break;
                        }else if(length == 0){
                            System.out.println("transfer complete!!!!");
                            break;
                        }else{
                            byteBuffer.flip();
                            byte[] bytes = new byte[byteBuffer.limit()];
                            byteBuffer.get(bytes);
                            System.out.println(new String(bytes));
                            byteBuffer.clear();
                        }

                    }
                }

            }
        }
    }
}
